package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.DeviceDataPageDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.IotMsgBody;
import com.zzyl.nursing.vo.IotMsgNotifyData;
import com.zzyl.nursing.vo.IotMsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 设备数据Service业务层处理
 * 
 * @author yjr
 * @date 2025-05-25
 */
@Slf4j
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IDeviceService iDeviceService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 添加设备数据信息
     *
     * @param contentStr
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addDeviceData(String contentStr) {
        //1.判断数据是否存在
        if (StringUtils.isBlank(contentStr)){
            return;
        }

        JSONObject contentStrJson = JSONUtil.parseObj(contentStr);
        JSONObject notifyDataJson = contentStrJson.getJSONObject("notify_data");
        JSONObject bodyJson = notifyDataJson.getJSONObject("body");
        if (notifyDataJson==null || bodyJson==null){
            return;
        }

        //2.解析数据
        IotMsgNotifyData notifyData = JSONUtil.toBean(notifyDataJson, IotMsgNotifyData.class);
        IotMsgBody body = JSONUtil.toBean(bodyJson, IotMsgBody.class);
        String deviceId = notifyData.getHeader().getDeviceId();
        Device device = iDeviceService.lambdaQuery().eq(Device::getIotId, deviceId).one();
        List<IotMsgService> services = body.getServices();

        //3.整理封装数据
        List<DeviceData> deviceDataList = new ArrayList<>();
        services.forEach(x->{
            String eventTimeStr = x.getEventTime();
            LocalDateTime eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            x.getProperties().forEach((k,v)->{
                DeviceData data = new DeviceData();
                BeanUtils.copyProperties(device, data);
                data.setId(null);
                data.setAlarmTime(eventTime);
                data.setAccessLocation(device.getBindingLocation());
                data.setFunctionId(k);
                data.setDataValue(String.valueOf(v));
                deviceDataList.add(data);
            });
        });

        //4.添加到本地数据库
        if (CollUtil.isNotEmpty(deviceDataList)){
            boolean result = false;
            try {
                result = this.saveBatch(deviceDataList);
            } catch (Exception e) {
                log.error("错误信息是:", e);
            }
            if (!result){
                throw new BaseException("添加设备数据失败");
            }
            log.info("添加设备数据成功,添加{}条", deviceDataList.size());
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA_KEY, deviceId, JSONUtil.toJsonStr(deviceDataList));
        }

    }

    /**
     * 查询设备数据列表
     *
     * @param dto
     * @return
     */
    @Override
    public Page<DeviceData> pageList(DeviceDataPageDto dto) {

        Page<DeviceData> page = this.lambdaQuery()
                .between(dto.getStartTime() != null && dto.getEndTime() != null, DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime())
                .like(StringUtils.isNotBlank(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .eq(StringUtils.isNotBlank(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .page(new Page<>(dto.getPageNum(), dto.getPageSize()));

        return page;
    }
}
